import { PageContainer } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Pagination, message, Spin } from 'antd';
import { useNavigate } from 'react-router-dom';
import { listInterfaceInfoByOnlinePageUsingGet } from '@/services/Kapi-backend/interfaceInfoController';

const { Meta } = Card;

const Index: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<API.InterfaceInfo[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [current, setCurrent] = useState<number>(1);
  const [selectedRowsState, setSelectedRows] = useState<API.InterfaceInfo[]>([]);
  const [pageSize] = useState<number>(10);
  const navigate = useNavigate();

  const loadData = async (currentPage = 1) => {
    setLoading(true);
    try {
      const res = await listInterfaceInfoByOnlinePageUsingGet({
        current: currentPage,
        pageSize,
      });
      setList(res?.data?.records ?? []);
      setTotal(res?.data?.total ?? 0);
      setCurrent(currentPage);
    } catch (error: any) {
      message.error('请求失败，' + error.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  const handlePageChange = (page: number) => {
    loadData(page);
  };

  const handleCardClick = (id: number) => {
    navigate(`/interface_info/${id}`);
  };

  return (
    <PageContainer title="在线接口开放平台">
      <div style={{ padding: '20px' }}>
        <Row gutter={[16, 16]}>
          {list.map((item) => (
            <Col xs={24} sm={12} md={8} lg={6} key={item.id}>
              <Card
                title={item.name}
                extra={<span style={{ color: '#52c41a' }}>&bull;</span>}
                hoverable
                onClick={() => handleCardClick(item.id)}
              >
                <p>{item.description}</p>
                <div style={{ marginTop: '10px', display: 'flex', justifyContent: 'space-between' }}>
                  <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万
                  </span>
                  {/*<span>*/}
                  {/*  <i className="anticon anticon-api" /> RESTful API*/}
                  {/*</span>*/}
                </div>
              </Card>
            </Col>
          ))}
        </Row>
        <div style={{ marginTop: '20px', textAlign: 'center' }}>
          <Pagination
            current={current}
            pageSize={pageSize}
            total={total}
            onChange={handlePageChange}
            showSizeChanger={false}
          />
          {loading && <Spin tip="加载中..." />}
        </div>
      </div>
    </PageContainer>
  );
};

export default Index;
